import axios from "axios";
import { Message } from "view-design";
axios.defaults.baseURL="/api"

axios.interceptors.request.use(config=>{
    return config;
},error => {
    return Promise.reject(error);
})


//添加响应拦截器
axios.interceptors.response.use(response=>{
    if(response.data.code && response.data.code == "401"){
        Message.error(response.data.msg)
    }
    //获取后端返回的对象
   return response;
},error => {
    alert(error.response.status)
    return Promise.reject(error);
})

export default {
    /**
     * 获取资源
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    get(url, params) {
        return new Promise((resolve, reject) => {
            axios.get(url, params)
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err)
                })
        });
    },
    /**
     * 添加资源或者获取资源
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    post(url,params){
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err)
                })
        });
    },
    /**
     * 删除资源
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    delete(url, params){
        return new Promise((resolve, reject) =>{
            axios.delete(url, params)
                .then(res=>{
                    resolve(res)
                }).catch(err=>{
                reject(err)
            })
        })
    },
    /**
     * 更新资源
     * @param url
     * @param params
     * @returns {Promise<unknown>}
     */
    put(url, params){
        return new Promise((resolve, reject) =>{
            axios.put(url, params)
                .then(res=>{
                    resolve(res)
                }).catch(err=>{
                reject(err)
            })
        })
    },
}
